﻿using System;
using System.Collections.Generic;
using System.Text;
using WTest.Model;
using System.Text.RegularExpressions;
using DaiChong.Lib.Http;
using System.Windows.Forms;
using System.Threading;

namespace WTest
{
    public class AsyncQiyi : AsyncBase
    {
        public string SiteName { get; set; }

        protected override void AsyncWork()
        {
            List<MovieUrl> lst = new List<MovieUrl> { 
                //new MovieUrl("http://list.iqiyi.com/www/1/----------0--2-1-1-1---.html", 1)         //1电影
                new MovieUrl("http://list.iqiyi.com/www/2/------------2-1-1-1---.html", 2)          //2电视剧
                //new MovieUrl("http://list.iqiyi.com/www/4/------------2-1-1-1---.html", 3)             //3动漫
                //new MovieUrl("http://list.iqiyi.com/www/6/------------3-1-1-1---.html", 4)           //4综艺 热播
                //new MovieUrl("http://list.iqiyi.com/www/3/----------0--3-1-1-1---.html", 7)          //纪录片 热播
            };

            Submit web = new Submit()
            {
                Encode = Encoding.UTF8
            };

            string maxPageUrl = "";
            int maxPage = 0;
            Match mch;
            for (int i = 0; i < lst.Count; i++)
            {
                //打开列表，分析：详情url，播放url，名称
                try
                {
                    web.URL = lst[i].Url;
                    web.Get();
                    DoGet(web.Html, lst[i].Type);
                }
                catch (Exception ee)
                {
                    continue;
                }

                //计算总页数
                mch = Regex.Match(web.Html, @"href=""([^""]+?)"">([\d]+?)</a> <a data-key=""down""");
                if (mch.Success)
                {
                    maxPageUrl = mch.Groups[1].Value;
                    maxPage = Convert.ToInt32(mch.Groups[2].Value);
                    for (int j = 2; j < 3; j++)
                    {
                        web = new Submit()
                        {
                            Encode = Encoding.UTF8,
                            URL = maxPageUrl.Replace(maxPage.ToString(), j.ToString())
                        };
                        try
                        {
                            web.Get();
                            DoGet(web.Html, lst[i].Type);
                        }
                        catch (Exception ee)
                        {
                            continue;
                        }
                    }
                }
            }
        }

        private void DoGet(string html, int i)
        {
            switch (i)
            {
                case 1:
                    GetMovie(html, MovieType.未知);
                    break;
                case 2:
                    GetTv(html, TVType.未知);
                    break;
                case 3:
                    GetDm(html, i);
                    break;
                case 4:
                    GetZy(html, i);
                    break;
                case 7:
                    GetJlp(html, i);
                    break;
            }
        }

        private void GetMovie(string html, MovieType mt)
        {
            Submit web = new Submit()
            {
                Encode = Encoding.UTF8
            };

            Match mch = Regex.Match(html, @"class=""imgBg1"" href=""([^""]+?)"">[\s\S]+?title=""([^""]+?)""[\s\S]+?src=""([^""]+?)""[\s\S]+?主演：(.*?)\n[\s\S]+?<strong class=""fRed""><span>([^<]+?)<[\s\S]+?导演：(.*?)\n[\s\S]+?类型：</span><[^>]+?>([^<]+?)</a> <[^>]+?>([^<]+?)<[\s\S]+?(http:\/\/t\.qiyi\.com/m/[^""]+?)"" target=""_blank"">介绍</a>");
            while (mch.Success)
            {
                Movie m = new Movie(SiteName);
                m.vod_play = "qiyi";
                m.vod_name = mch.Groups[2].Value.Replace("'", "‘").Trim(); //名称
                m.vod_pic = mch.Groups[3].Value;
                m.vod_pic = "/getpic.php?img=" + m.vod_pic.Replace("_160_90", "");
                m.vod_gold = mch.Groups[5].Value;
                m.vod_area = mch.Groups[7].Value;
                m.vod_cid = GetMovieType(mch.Groups[8].Value);

                if (m.Exist(m.vod_name))
                {
                    mch = mch.NextMatch();
                    continue;
                }

                //演员
                string actors = "";
                Match mch2 = Regex.Match(mch.Groups[4].Value, @"href=""[^>]+?>([^<]+?)</a>");
                while (mch2.Success)
                {
                    actors += " " + mch2.Groups[1].Value;
                    mch2 = mch2.NextMatch();
                }
                m.vod_actor = actors;

                //演员
                string directors = "";
                mch2 = Regex.Match(mch.Groups[6].Value, @"href=""[^>]+?>([^<]+?)</a>");
                while (mch2.Success)
                {
                    directors += " " + mch2.Groups[1].Value;
                    mch2 = mch2.NextMatch();
                }
                m.vod_director = directors;

                //播放地址
                try
                {
                    web.URL = mch.Groups[1].Value;
                    web.Get();
                }
                catch (Exception)
                {
                    continue;
                }
                mch2 = Regex.Match(web.Html, @"videoId"":""([^""]+?)""");
                if (!mch2.Success)
                {
                    mch = mch.NextMatch();
                    continue;
                }
                m.vod_url = mch2.Groups[1].Value;

                //打开详情页，图片
                try
                {
                    web.URL = mch.Groups[9].Value;
                    web.Get();
                }
                catch (Exception)
                {
                    mch = mch.NextMatch();
                    continue;
                }

                //其他明细信息
                mch2 = Regex.Match(web.Html, @"上映时间：<span>[^>]+?>([^<]+?)<");
                if (mch2.Success)
                    m.vod_year = mch2.Groups[1].Value;

                //打开/detail简介页，简介
                web.URL = mch.Groups[9].Value + "/detail";
                web.Get();
                mch2 = Regex.Match(web.Html, @"<p class=""starinfo-txt"">([\s\S]+?)</p>");
                if (mch2.Success)
                    m.vod_content = mch2.Groups[1].Value.Replace("'", "‘");

                if (!string.IsNullOrEmpty(m.vod_url))
                {
                    m.Insert(m);
                    OnMessage(this, string.Format("{0}Add Mv:{1}", Environment.NewLine, m.vod_name));
                }
                Thread.Sleep(100);

                mch = mch.NextMatch();
            }
        }

        private void GetTv(string html, TVType tt)
        {
            Submit web = new Submit()
            {
                Encode = Encoding.UTF8
            };

            Match mch = Regex.Match(html, @"class=""imgBg1"" href=""([^""]+?)"">[\s\S]+?title=""([^""]+?)""[\s\S]+?src=""([^""]+?)""[\s\S]+?([\d]+?)集[\s\S]+?主演：(.*?)\n[\s\S]+?<strong class=""fRed""><span>([^<]+?)<[\s\S]+?导演：(.*?)\n[\s\S]+?类型：</span><[^>]+?>([^<]+?)<");
            Match mch2;
            string actors = ""; //主演
            string directors = "";//导演
            while (mch.Success)
            {
                Movie m = new Movie(SiteName);
                m.vod_play = "qiyi";
                m.vod_url = mch.Groups[1].Value;  //电视剧专辑页
                m.vod_name = mch.Groups[2].Value.Replace("'", "‘").Trim(); //名称
                m.vod_pic = mch.Groups[3].Value;
                m.vod_pic = "/getpic.php?img=" + m.vod_pic.Replace("_160_90", "");
                if (mch.Groups[0].Value.Contains("集全"))
                    m.vod_continu = 0;
                else
                    m.vod_continu = Convert.ToInt32(mch.Groups[4].Value);
                m.vod_gold = mch.Groups[6].Value;

                int vod_id = 0;
                int vod_continu = 0;
                bool bExist = m.Exist(m.vod_name, out vod_id, out vod_continu);
                m.vod_id = vod_id;
                //判断是否成功
                if (bExist && (vod_continu == 0 || vod_continu == m.vod_continu))
                {
                    mch = mch.NextMatch();
                    continue;
                }

                if (!bExist)//不存在，继续正则其他信息
                {
                    //主演
                    mch2 = Regex.Match(mch.Groups[5].Value, @">([^<]+?)</a");
                    while (mch2.Success)
                    {
                        actors += " " + mch2.Groups[1].Value;
                        mch2 = mch2.NextMatch();
                    }
                    m.vod_actor = actors;

                    //导演
                    mch2 = Regex.Match(mch.Groups[7].Value, @">([^<]+?)</a");
                    while (mch2.Success)
                    {
                        directors += " " + mch2.Groups[1].Value;
                        mch2 = mch2.NextMatch();
                    }
                    m.vod_director = directors;

                    //类型 CID
                    m.vod_area = mch.Groups[8].Value;
                    if (tt == TVType.未知)
                        m.vod_cid = GetTVType(m.vod_area);
                }

                //打开专辑页面
                web.URL = m.vod_url;  //电视剧专辑页
                try
                {
                    web.Get();
                    m.vod_url = GetTvFlvs(web.Html);
                }
                catch (Exception)
                {
                    mch = mch.NextMatch();
                    continue;
                }

                //简介
                if (!bExist)
                {
                    mch2 = Regex.Match(web.Html, @"<meta name=""description"" content=""([^""]+?)""");
                    if (mch2.Success)
                        m.vod_content = mch2.Groups[1].Value.Replace("'", "‘");
                }

                if (!bExist && !string.IsNullOrEmpty(m.vod_url))
                {
                    m.Insert(m);
                    OnMessage(this, string.Format("{0}Add Tv:{1}", Environment.NewLine, m.vod_name));
                }
                if (bExist && !string.IsNullOrEmpty(m.vod_url))
                {
                    m.ReplaceUrl(m);
                    OnMessage(this, string.Format("{0}Update Tv:{1}", Environment.NewLine, m.vod_name));
                }

                mch = mch.NextMatch();
            }
        }

        private void GetDm(string html, int cid)
        {
            Submit web = new Submit()
            {
                Encode = Encoding.UTF8
            };

            MatchCollection mchs = Regex.Matches(html, @"<strong class=""fRed""><span>([^<]+?)<([\s\S]+?)<span>类型：</span><a href=""[^""]+?"">([^<]+?)<");
            Match mch2;
            foreach (Match mch in mchs)
            {
                Movie m = new Movie(SiteName)
                {
                    vod_cid = cid,
                    vod_play = "qiyi",
                    vod_gold = mch.Groups[1].Value,
                    vod_area = mch.Groups[3].Value
                };

                m.vod_url = Regex.Match(mch.Groups[2].Value, @"class=""imgBg1"" href=""([^""]+?)""").Groups[1].Value;
                mch2 = Regex.Match(mch.Groups[2].Value, @"alt=""([^""]+?)"" src=""([^""]+?)""");
                m.vod_name = mch2.Groups[1].Value.Replace("'", "‘").Trim();
                m.vod_pic = mch2.Groups[2].Value;
                m.vod_pic = "/getpic.php?img=" + m.vod_pic.Replace("_160_90", "");

                mch2 = Regex.Match(mch.Groups[2].Value, @">.*?([\d]+?)集[全]?<");                
                //单集
                if (!mch2.Success)
                {
                    if (m.Exist(m.vod_name))
                        continue;

                    //播放地址
                    try
                    {
                        web.URL = m.vod_url;
                        web.Get();
                    }
                    catch (Exception)
                    {
                        continue;
                    }
                    mch2 = Regex.Match(web.Html, @"videoId"":""([^""]+?)""");
                    if (!mch2.Success)
                        continue;
                    m.vod_url = mch2.Groups[1].Value;

                    if (!string.IsNullOrEmpty(m.vod_url))
                    {
                        m.Insert(m);
                        OnMessage(this, string.Format("{0}Add Dm:{1}", Environment.NewLine, m.vod_name));
                    }
                }
                else//多集
                {
                    if (mch.Groups[2].Value.Contains("集全"))
                        m.vod_continu = 0;
                    else
                        m.vod_continu = Convert.ToInt32(Regex.Match(mch.Groups[2].Value, @">.*?([\d]+?)集[全]?<").Groups[1].Value);

                    int vod_id = 0;
                    int vod_continu = 0;
                    bool bExist = m.Exist(m.vod_name, out vod_id, out vod_continu);
                    m.vod_id = vod_id;
                    //判断是否成功
                    if (bExist && (vod_continu == 0 || vod_continu == m.vod_continu))
                        continue;

                    //打开专辑页面
                    web.URL = m.vod_url;  //电视剧专辑页
                    try
                    {
                        web.Get();
                        m.vod_url = GetTvFlvs(web.Html);
                    }
                    catch (Exception)
                    {
                        continue;
                    }

                    //简介
                    if (!bExist)
                    {
                        mch2 = Regex.Match(web.Html, @"<meta name=""description"" content=""([^""]+?)""");
                        if (mch2.Success)
                            m.vod_content = mch2.Groups[1].Value.Replace("'", "‘");
                    }

                    if (!bExist && !string.IsNullOrEmpty(m.vod_url))
                    {
                        m.Insert(m);
                        OnMessage(this, string.Format("{0}Add Dm:{1}", Environment.NewLine, m.vod_name));
                    }
                    if (bExist && !string.IsNullOrEmpty(m.vod_url))
                    {
                        m.ReplaceUrl(m);
                        OnMessage(this, string.Format("{0}Update Dm:{1}", Environment.NewLine, m.vod_name));
                    }
                }
            }
        }

        private void GetZy(string html, int cid)
        {
            Submit web = new Submit()
            {
                Encode = Encoding.UTF8
            };

            Match mch2;
            string tmp = "";
            string directors = "";
            string actors = "";
            MatchCollection mchs = Regex.Matches(html, @"<a   class=""imgBg1"" href=""([^""]+?)""([\s\S]+?)<span>类型：</span><[^>]+?>([^<]+?)<");
            foreach (Match mch in mchs)
            {
                Movie m = new Movie(SiteName)
                {
                    vod_cid = cid,
                    vod_play = "qiyi",
                    vod_url = mch.Groups[1].Value,
                    vod_area = mch.Groups[3].Value
                };
                m.vod_name = Regex.Match(mch.Groups[2].Value, @" title=""([^""]+?)""").Groups[1].Value.Replace("'", "‘").Trim();

                if (m.Exist(m.vod_name))
                {
                    continue;
                }

                m.vod_pic = Regex.Match(mch.Groups[2].Value, @" src=""([^""]+?)""").Groups[1].Value;
                m.vod_pic = "/getpic.php?img=" + m.vod_pic.Replace("_160_90", "");
                m.vod_title = Regex.Match(mch.Groups[2].Value, @"<span>栏目：<a [^>]+?>([^<]+?)</a></span>").Groups[1].Value;     //快乐大本营
                m.vod_keywords = Regex.Match(mch.Groups[2].Value, @" class=""imgBg1C"">([^<]+?)</span>").Groups[1].Value;         //第2012-08-04期

                tmp = Regex.Match(mch.Groups[2].Value, @"<span>主持：([^\n]+?)\n").Groups[1].Value;
                mch2 = Regex.Match(tmp, @">([^<]+?)</a");
                while (mch2.Success)
                {
                    directors += " " + mch2.Groups[1].Value;
                    mch2 = mch2.NextMatch();
                }
                m.vod_director = directors;

                tmp = Regex.Match(mch.Groups[2].Value, @"<span>嘉宾：([^\n]+?)\n").Groups[1].Value;
                mch2 = Regex.Match(tmp, @">([^<]+?)</a");
                while (mch2.Success)
                {
                    actors += " " + mch2.Groups[1].Value;
                    mch2 = mch2.NextMatch();
                }
                m.vod_actor = actors;

                //打开详情页 播放地址
                try
                {
                    web.URL = m.vod_url;
                    web.Get();
                }
                catch (Exception)
                {
                    continue;
                }
                mch2 = Regex.Match(web.Html, @"videoId"":""([^""]+?)""");
                if (!mch2.Success)
                    continue;
                m.vod_url = mch2.Groups[1].Value;

                //详细信息
                string contents = "";
                mch2 = Regex.Match(web.Html, @"<dd class=""dd_kd""><a href=""#"">([^<]+?)</a></dd>");
                int i = 1;
                while (mch2.Success)
                {
                    contents += string.Format(" 看点{0}:{1}", i, mch2.Groups[1].Value);
                    i++;
                    mch2 = mch2.NextMatch();
                }
                m.vod_content = string.Format("{0} {1} {2}<br>{3}", m.vod_title, m.vod_keywords, m.vod_name, contents);

                if (!string.IsNullOrEmpty(m.vod_url))
                {
                    m.Insert(m);
                    OnMessage(this, string.Format("{0}Add Zy:{1}", Environment.NewLine, m.vod_name));
                }
                Thread.Sleep(100);
            }
        }

        private void GetJlp(string html, int cid)
        {
            Submit web = new Submit()
            {
                Encode = Encoding.UTF8
            };

            Match mch2;
            MatchCollection mchs = Regex.Matches(html, @"class=""imgBg1"" href=""([^""]+?)"">[\s\S]+?alt=""([^""]+?)"" src=""([^""]+?)""([\s\S]+?)</a>");
            foreach (Match mch in mchs)
            {
                Movie m = new Movie(SiteName)
                {
                    vod_cid = cid,
                    vod_play = "qiyi",
                    vod_url = mch.Groups[1].Value,
                    vod_name = mch.Groups[2].Value,
                    vod_pic = mch.Groups[3].Value
                };
                m.vod_pic = "/getpic.php?img=" + m.vod_pic.Replace("_160_90", "");

                //单集还是多集
                mch2 = Regex.Match(mch.Groups[4].Value, @"<span class=""imgBg1C"">[^\d]+?([\d]+?)集[全]?</span>");

                //单集
                if (!mch2.Success)
                {
                    if (m.Exist(m.vod_name))
                        continue;

                    //播放地址
                    try
                    {
                        web.URL = m.vod_url;
                        web.Get();
                    }
                    catch (Exception)
                    {
                        continue;
                    }
                    mch2 = Regex.Match(web.Html, @"videoId"":""([^""]+?)""");
                    if (!mch2.Success)
                        continue;
                    m.vod_url = mch2.Groups[1].Value;

                    if (!string.IsNullOrEmpty(m.vod_url))
                    {
                        m.Insert(m);
                        OnMessage(this, string.Format("{0}Add Jlp:{1}", Environment.NewLine, m.vod_name));
                    }
                }
                else //多集
                {
                    if (mch.Groups[0].Value.Contains("集全"))
                        m.vod_continu = 0;
                    else
                        m.vod_continu = Convert.ToInt32(mch2.Groups[1].Value);

                    int vod_id = 0;
                    int vod_continu = 0;
                    bool bExist = m.Exist(m.vod_name, out vod_id, out vod_continu);
                    m.vod_id = vod_id;
                    //判断是否成功
                    if (bExist && (vod_continu == 0 || vod_continu == m.vod_continu))
                        continue;

                    //打开专辑页面
                    try
                    {
                        web.URL = m.vod_url;  //电视剧专辑页
                        web.Get();
                        m.vod_url = GetTvFlvs(web.Html);
                    }
                    catch (Exception)
                    {
                    }

                    //简介
                    if (!bExist)
                    {
                        mch2 = Regex.Match(web.Html, @"<meta name=""description"" content=""([^""]+?)""");
                        if (mch2.Success)
                            m.vod_content = mch2.Groups[1].Value.Replace("'", "‘");
                    }

                    if (!bExist && !string.IsNullOrEmpty(m.vod_url))
                    {
                        m.Insert(m);
                        OnMessage(this, string.Format("{0}Add Jlp:{1}", Environment.NewLine, m.vod_name));
                    }
                    if (bExist && !string.IsNullOrEmpty(m.vod_url))
                    {
                        m.ReplaceUrl(m);
                        OnMessage(this, string.Format("{0}Update Jlp:{1}", Environment.NewLine, m.vod_name));
                    }

                }

                Thread.Sleep(100);
            }
        }

        private string GetTvFlvs(string html)
        {
            int number = 1;
            string vid = "0"; //专辑id
            string id = "0";  //id

            Match mch;
            vid = Regex.Match(html, "\"albumId\":([^,]+?),").Groups[1].Value;

            if (html.Contains("cmsSubjectId"))
            {
                mch = Regex.Match(html, "\"cmsSubjectId\":([^,]+?),");
                if (mch.Success)
                    id = mch.Groups[1].Value;
                else
                {
                    mch = Regex.Match(html, "cmsSubjectId = ([^;]+?);");
                    if (mch.Success)
                        id = mch.Groups[1].Value;
                }
                int total = Convert.ToInt32(Regex.Match(html, "\"currentMaxEpisode\":([^,]+?),").Groups[1].Value);
                double count = Convert.ToDouble(total) / 75;
                number = Convert.ToInt32(Math.Ceiling(count));
            }
            else
            {
                id = Regex.Match(html, "\"pid\":\"([^,]+?),\"").Groups[1].Value;
            }

            Submit web = new Submit()
            {
                Encode = Encoding.UTF8
            };

            string urls = "";
            string url = "";
            //string sname = "";
            for (int i = 0; i < number; i++)
            {
                web.URL = string.Format("http://cache.video.qiyi.com/avlist/{0}/{1}/2/{2}/", vid, id, i + 1);
                web.Get();
                //mch = Regex.Match(web.Html, @"""pd"":([^,]+?),.*?""vt"":""([^""]*?)"".*?""vid"":""([^""]+?)""");
                mch = Regex.Match(web.Html, @"""pd"":([^,]+?),.*?""vt"":""([^""]*?)"".*?""vid"":""([^""]+?)"",""vn"":""([^""]*?)""");
                while (mch.Success)
                {
                    //sname = mch.Groups[2].Value;
                    url = string.Format("{0}:{1}${2}"
                        , mch.Groups[1].Value
                        , mch.Groups[2].Value == "" ? mch.Groups[4].Value : mch.Groups[2].Value
                        , mch.Groups[3].Value);

                    url = url.Replace("'", "‘");
                    if (string.IsNullOrEmpty(urls))
                        urls = url;
                    else
                        urls += "\r\n" + url;
                    mch = mch.NextMatch();
                }
            }

            return urls;
        }

        public int GetMovieType(string leMovieType)
        {
            MovieType mt = MovieType.剧情片;

            switch (leMovieType)
            {
                case "动作":
                    mt = MovieType.动作片;
                    break;
                case "喜剧":
                    mt = MovieType.喜剧片;
                    break;
                case "爱情":
                case "惊辣":
                case "青春":
                    mt = MovieType.爱情片;
                    break;
                case "科幻":
                case "魔幻":
                    mt = MovieType.科幻片;
                    break;
                case "恐怖":
                case "灾难":
                    mt = MovieType.恐怖片;
                    break;
                case "战争":
                case "枪战":
                    mt = MovieType.战争片;
                    break;
                case "剧情":
                case "悲剧":
                case "艺术":
                case "传记":
                    mt = MovieType.剧情片;
                    break;
            }

            return (int)mt;
        }

        public int GetTVType(string leTVType)
        {
            TVType tvType = TVType.海外剧;

            switch (leTVType)
            {
                case "内地":
                    tvType = TVType.国产剧;
                    break;
                case "香港":
                case "台湾":
                    tvType = TVType.港台剧;
                    break;
                case "美剧":
                    tvType = TVType.欧美剧;
                    break;
                case "日本":
                case "韩国":
                    tvType = TVType.日韩剧;
                    break;
                case "泰国":
                    tvType = TVType.海外剧;
                    break;
            }

            return (int)tvType;
        }

    }
}
